/* Copyright 2008 Shawn C. Dodd

This file is part of TagFC.  TagFC is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

TagFC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License along with TagFC.  If not, see <http://www.gnu.org/licenses/>. */

import org.hibernate.*;

class PieceController {
	SessionFactory sessionFactory		// inject Hibernate session

	def scaffold = Piece

	def sort = {
		def hibSession = sessionFactory.getCurrentSession()

		// got a list of checked checkboxes?
		if( params.containsKey('updateChoices') ) {
			HashSet checked = new HashSet(50)
			int delCount = 0
			// got a POST
			params.each { 
				if( it =~ /=on$/ ) checked.add((it =~ /^cb(\d+)=on$/)[0][1])
			}
			params.each {
				// process checked and unchecked images
				if( it =~ /^_cb/ ) {
					def num = (it =~ /^_cb(\d+)=/)[0][1]
//					log.error "num: ${num}"
					if( checked.contains(num) ) {
						// checked, so tag and change state
						tag( num, "car", session.getAttribute('nickname') )
					} else {
						// unchecked, so delete
						del( num, session.getAttribute('nickname') )
						delCount++
//						log.error "del: ${num}"	// TODO  for debugging; change to all on one line
					}
				}
			}
			// TODO  update user stats here (tagged, discarded, etc.)
			log.error "Discarded $delCount pieces by (${session.getAttribute('nickname')})" 
			hibSession.flush()
		}

		// produce the next grid from list()
		if(!params.max) params.max = 100
		if(!params.offset) params.offset = 0
		[ pieceList: Piece.findAllByState("unproc", [sort:"dateCreated",order:"asc",max:params.max,offset:params.offset]) ]	
	}

	def discard = {
	}

	void tag( String pid, String tags, String nickname ) {
                // TODO  this code needs to go into a service (for reuse)
                def p = Piece.get(pid)
                p.simpleEntry.tags = tags
                p.state = "tagged"
                def saved = p.save()
                if(!saved) p.errors.allErrors.each { log.error "Problem tagging Piece ${pid}; $it" }
                else log.error "Successfully tagged Piece ${pid} by (${nickname})"
	}

	void del( String pid, String nickname ) {
		def p = Piece.get(pid)
		p.delete()
	}

	def tagged = {
		tag( params.id, "car", session.getAttribute('nickname') )
		chain(action:"show", id:p.id)
	}

	def flashMe = {
		flash.message = "Consider yourself flashed."
		redirect(controller:"piece",action:sort)
	}

//    def index = { }
}
